package site.service.weibo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;

import site.entity.Weibo;
import site.entity.WeiboUserInfo;

/**
 * 
 * @author JinJing
 *
 */
public class WeiboMessageListGenerator {

	public static List<Weibo> generateLatestMessageList(List<WeiboUserInfo> weiboUserInfoList, int weiboCount) {
		List<Weibo> latestMessageList = new ArrayList<Weibo>();
		if(weiboUserInfoList == null || weiboCount <= 0) {
			return latestMessageList;
		}
		
		List<List<Weibo>> weiboLists = new ArrayList<List<Weibo>>();	
		
		for(int i = 0; i < weiboUserInfoList.size(); i++) {
			List<Weibo> singleWeiboList = getSingleWeiboList(weiboUserInfoList.get(i), weiboCount);
			weiboLists.add(singleWeiboList);
		}
		
		latestMessageList = mergeWeiboList(weiboLists, weiboCount);
			
		return latestMessageList;
	}
	
	private static List<Weibo> getSingleWeiboList(WeiboUserInfo weiboUserInfo, int weiboCount) {
		List<Weibo> weiboList = new ArrayList<Weibo>();
		String weiboMessageURL = "http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=550&fansRow=2&ptype=1&speed=0&skin=1&isTitle=1&noborder=1&isWeibo=1&isFans=1&uid=" + weiboUserInfo.getUid() + "&verifier=" + weiboUserInfo.getVerifier();
		System.out.println();
		String page = HttpPage.getPageByHttpClient(weiboMessageURL);
		if(page == null) {
			return weiboList;
		}
		
		String imgURL = null;
		try {
			Parser parser = new Parser();
			parser.setInputHTML(page);
			NodeFilter filter = new TagNameFilter("img");
			NodeList nodeList = parser.parse(filter);
			Node node = nodeList.elementAt(0);
			String imgTag = node.getText();
			if(imgTag.contains("http://tp4.sinaimg.cn")) {
				int beginIndex, endIndex;
				beginIndex = imgTag.indexOf("src=\"") + 5;
				endIndex = imgTag.indexOf("\"", beginIndex);
				imgURL = new String(imgTag.substring(beginIndex, endIndex));
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String userName = null;
		try {
			int beginIndex, endIndex;
			beginIndex = page.indexOf("<strong>") + 8;
			endIndex = page.indexOf("</strong>", beginIndex);
			userName = new String(page.substring(beginIndex, endIndex));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			Parser parser = new Parser();
			parser.setInputHTML(page);
			NodeFilter filter = new HasAttributeFilter("class", "mbTxtB");
			NodeList nodeList = parser.parse(filter);
		
			Parser parser2 = new Parser();
			parser2.setInputHTML(page);
			NodeFilter filter2 = new HasAttributeFilter("class", "wbLinkC");
			NodeList nodeList2 = parser2.parse(filter2);
			
			if(nodeList.size() != nodeList2.size())
			{
				return weiboList;
			}
			
			for(int i = 0; i < nodeList.size() && i < weiboCount; i++)
			{
			
				Node node = nodeList.elementAt(i);
				String messageHtml = node.toHtml();
				
				int beginIndex, endIndex;
				
				beginIndex = messageHtml.indexOf(">") + 1;
				endIndex = messageHtml.indexOf("</span>");
				
				String message = messageHtml.substring(beginIndex, endIndex);

				Node node2 = nodeList2.elementAt(i);
				String postTimeString = node2.toPlainTextString();
				
				Date postTime = changeWeiboPostTimeFormat(postTimeString);
				
				Weibo weibo = new Weibo();
				weibo.setImageURL(imgURL);
				weibo.setUserName(userName);
				weibo.setMessage(message);
				weibo.setPostTime(postTime);
				
				weiboList.add(weibo);				
			}
		} catch (Exception e) {
			e.printStackTrace();
			return weiboList;
		}
		
		return weiboList;
	}
	
	private static List<Weibo> mergeWeiboList(List<List<Weibo>> weiboLists, int weiboCount) {
		List<Weibo> weiboList = new ArrayList<Weibo>();
		if(weiboLists == null)
		{
			return weiboList;
		}
		while(weiboList.size() < weiboCount) {
			Weibo latestWeibo = null;
			int latestWeiboListID = 0;
			for(int i = 0; i < weiboLists.size(); i++) {
				List<Weibo> singleWeiboList = weiboLists.get(i);				
				if(singleWeiboList != null && singleWeiboList.size() != 0) {
					Weibo candidateWeibo = singleWeiboList.get(0);
					
					if(latestWeibo == null) {
						latestWeibo = candidateWeibo;
						latestWeiboListID = i;
						//System.out.println(i);
					}
					else {
						if(latestWeibo.getPostTime().before(candidateWeibo.getPostTime())) {
							latestWeibo = candidateWeibo;
							latestWeiboListID = i;
						}
					}
				}
			}
			if(latestWeibo == null) {
				break;
			}
			
			weiboList.add(latestWeibo);
			weiboLists.get(latestWeiboListID).remove(0);
		}
		return weiboList;
	}
	
	private static Date changeWeiboPostTimeFormat(String postTimeString) {
		Calendar cal = Calendar.getInstance();
		Date currentTime = cal.getTime();
		Long postTimeLong = currentTime.getTime();
		
		postTimeString = postTimeString.trim();
		
		try {
			Date postTime = new Date();
			if(postTimeString.contains("秒前")) {
				int beginIndex, endIndex;
				beginIndex = 0;
				endIndex = postTimeString.indexOf("秒前");
				Long relativeTime = Long.valueOf(postTimeString.substring(beginIndex, endIndex)) * 1000;
				postTimeLong = postTimeLong - relativeTime;
				postTime.setTime(postTimeLong);
			}
			
			if(postTimeString.contains("分钟前")) {
				int beginIndex, endIndex;
				beginIndex = 0;
				endIndex = postTimeString.indexOf("分钟前");
				Long relativeTime = Long.valueOf(postTimeString.substring(beginIndex, endIndex)) * 60 * 1000;
				postTimeLong = postTimeLong - relativeTime;
				postTime.setTime(postTimeLong);
			}
			
			if(postTimeString.contains("今天")) {
				int beginIndex, endIndex;
				
				int year, month, date;
				int hour, minute, second;
				
				year = cal.get(Calendar.YEAR);
				month = cal.get(Calendar.MONTH);
				date = cal.get(Calendar.DATE);
				
				String time = postTimeString.split(" ")[1];
				
				beginIndex = 0;
				endIndex = time.indexOf(":");
				hour = Integer.valueOf(time.substring(beginIndex, endIndex));
				
				beginIndex = endIndex + 1;
				minute = Integer.valueOf(time.substring(beginIndex));
				second = 0;
				cal.set(year, month, date, hour, minute, second);
				postTime = cal.getTime();
			}
			
			if(postTimeString.contains("月")) {
				int beginIndex, endIndex;
				
				int year, month, date;
				int hour, minute, second;
				
				year = cal.get(Calendar.YEAR);
				
				String monthString = postTimeString.split("月")[0];
				month = Integer.valueOf(monthString) - 1;
				
				
				String dateString = postTimeString.split("月")[1].split("日")[0];
				date = Integer.valueOf(dateString);
				
				String time = postTimeString.split(" ")[1];
				
				beginIndex = 0;
				endIndex = time.indexOf(":");
				hour = Integer.valueOf(time.substring(beginIndex, endIndex));
				
				beginIndex = endIndex + 1;
				minute = Integer.valueOf(time.substring(beginIndex));
				second = 0;
				cal.set(year, month, date, hour, minute, second);
				postTime = cal.getTime();
			}
			
			if(postTimeString.contains("-")) {
				int beginIndex, endIndex;
				
				int year, month, date;
				int hour, minute, second;
				
				String dayString = postTimeString.split(" ")[0];
				String yearString = dayString.split("-")[0];
				year = Integer.valueOf(yearString);
				
				String monthString = dayString.split("-")[1];
				month = Integer.valueOf(monthString) - 1;
				
				String dateString = dayString.split("-")[2];
				date = Integer.valueOf(dateString);
				
				String time = postTimeString.split(" ")[1];
				
				beginIndex = 0;
				endIndex = time.indexOf(":");
				hour = Integer.valueOf(time.substring(beginIndex, endIndex));
				
				beginIndex = endIndex + 1;
				minute = Integer.valueOf(time.substring(beginIndex));
				second = 0;
				cal.set(year, month, date, hour, minute, second);
				postTime = cal.getTime();
			}
			return postTime;
		
		} catch (Exception e) {
			return currentTime;
		}
		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		/*Calendar cal = Calendar.getInstance();
		System.out.println(cal.getTime());
		System.out.println(cal.get(Calendar.YEAR));
		System.out.println(cal.get(Calendar.MONTH));
		System.out.println(cal.get(Calendar.DATE));
		System.out.println(cal.get(Calendar.HOUR_OF_DAY));
		System.out.println(cal.get(Calendar.MINUTE));
		System.out.println(cal.get(Calendar.SECOND));
		cal.set(Calendar.YEAR, 2010);
		System.out.println(cal.getTime());*/
		/*Date postTime = new Date();
		System.out.println(postTime);
		postTime.setTime(123455677);
		System.out.println(postTime);*/
		/*Calendar cal = Calendar.getInstance();
		System.out.println(cal.getTime());
		Date date = changeWeiboPostTimeFormat("30秒前");
		System.out.println(date);
		date = changeWeiboPostTimeFormat("5分钟前");
		System.out.println(date);
		date = changeWeiboPostTimeFormat("今天 16:14");
		System.out.println(date);
		date = changeWeiboPostTimeFormat("11月7日 22:36");
		System.out.println(date);
		date = changeWeiboPostTimeFormat("2010-12-24 17:25");
		System.out.println(date);*/
		List<WeiboUserInfo> weiboUserInfoList = new ArrayList<WeiboUserInfo>();
		
		WeiboUserInfo weiboUserInfo = new WeiboUserInfo();
		weiboUserInfo.setUid("2005163655");
		weiboUserInfo.setVerifier("6aac0f18");
		weiboUserInfoList.add(weiboUserInfo);
		
		weiboUserInfo = new WeiboUserInfo();
		weiboUserInfo.setUid("2003140083");
		weiboUserInfo.setVerifier("3e4ad68d");
		weiboUserInfoList.add(weiboUserInfo);
		
//		weiboUserInfo = new WeiboUserInfo();
//		weiboUserInfo.setUid("1505490043");
//		weiboUserInfo.setVerifier(verifier);
//		weiboUserInfoList.add(weiboUserInfo);
		
		List<Weibo> weiboMessageList = generateLatestMessageList(weiboUserInfoList, 20);
		for(int i = 0; i < weiboMessageList.size(); i++) {
			System.out.println("###############################################");
			System.out.println("imageURL: " + weiboMessageList.get(i).getImageURL());
			System.out.println("userName: " + weiboMessageList.get(i).getUserName());
			System.out.println("message: " + weiboMessageList.get(i).getMessage());
			System.out.println("postTime: " + weiboMessageList.get(i).getPostTime());
		}
	}

}
